package com.kotlin.android.simple.simple

import android.app.ProgressDialog
import androidx.activity.viewModels
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.jeremyliao.liveeventbus.LiveEventBus
import com.kotlin.android.core.BaseVMActivity
import com.kotlin.android.ktx.ext.*
import com.kotlin.android.ktx.utils.LogUtils
import com.kotlin.android.liveevent.LOGIN_SUCCESS
import com.kotlin.android.liveevent.event.LoginState
import com.kotlin.android.router.path.RouterActivityPath
import com.kotlin.android.simple.R
import kotlinx.android.synthetic.main.simple_main.*

/**
 *
 * Created on 2020/4/24.
 *
 * @author o.s
 */
@Route(path = RouterActivityPath.Simple.PAGER_SIMPLE_MVVM)
class SimpleMVVMActivity : BaseVMActivity<SimpleViewModel>(false) {

    private var progressDialog: ProgressDialog? = null

    override fun getLayoutResId() = R.layout.simple_main

    override fun initVM() = viewModels<SimpleViewModel>().value

    override fun initVariable() {
        intent.getIntExtra(KEY_SCREEN_WIDTH, 0).v()
        intent.getStringExtra(KEY_SCREEN_HEIGHT).v()
//        LogUtils.e("" + intent.extras)
    }

    override fun initView() {
//        ARouter.getInstance().inject(this);
        simpleRequest?.setOnClickListener {
            mViewModel?.loadData()
        }
    }

    override fun initData() {
        LiveEventBus.get(LOGIN_SUCCESS).post(LoginState(isLogin = true))//发送登录成功事件
    }

    override fun startObserve() {
        mViewModel?.apply {
            uiState.observe(this@SimpleMVVMActivity, Observer {
                it.apply {
                    if (showLoading) {
                        showLoadingView()
                    } else {
                        dismissLoadingView()
                    }

                    success?.apply {
                        // TODO 成功
                        simpleResponse?.text = it.toString()
                    }

                    error?.apply {
                        // TODO 错误
                        simpleResponse?.text = this
                    }

                    netError?.apply {
                        // TODO 网络错误
                        simpleResponse?.text = this
                    }

                    if (needLogin) {
                        // TODO 去登陆
                        toast("需要登录")
                    }
                }
            })
        }
    }

    private fun showLoadingView() {
        if (progressDialog == null) {
//            progressDialog = ProgressBar(this, null, android.R.attr.progressBarStyleLarge)
            progressDialog = ProgressDialog(this)
        }
        progressDialog?.show()
    }

    private fun dismissLoadingView() {
        if (progressDialog?.isShowing == true) {
            progressDialog?.dismiss()
        }
    }
}